<template>
  <div class="app-container">
    <el-form
      label-position="left"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="资源类型">
        <el-select
          v-model="queryParams.resourceType"
          placeholder="请选择资源类型"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:resource:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:resource:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:resource:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:resource:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :data="resourceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="thumbnail" label="缩略图">
        <template slot-scope="scope">
          <el-image :src="scope.row.img" />
        </template>
      </el-table-column>
      <el-table-column label="资源类型" align="center" prop="resourceType" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="单价，单位元/千克" align="center" prop="price" />
      <el-table-column label="重量，单位千克" align="center" prop="weight" />
      <!-- <el-table-column label="价格" align="center" prop="totalPrice" /> -->
      <el-table-column
        label="打包要求"
        align="center"
        prop="packageRequirements"
      />
      <el-table-column
        label="创建日期"
        align="center"
        prop="createTime"
        width="180px"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <!-- <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-unfold"
            @click="bindOrder(scope.row)"
            v-hasPermi="['system:notice:query']"
            >绑定到申请</el-button
          >
        </template> -->
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资源类型" prop="resourceType">
          <el-form-item label="图片附件" prop="img" label-width="80">
            <el-upload
              :action="imgUpload.url"
              :headers="imgUpload.headers"
              list-type="picture-card"
              :limit="limit"
              :on-exceed="handleExceed"
              :on-success="handlePictureSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePictureCardPreview"
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" v-if="imageUrl" :src="imageUrl" alt="" />
            </el-dialog>
          </el-form-item>

          <el-select
            v-model="form.resourceType"
            placeholder="请选择资源类型"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="单价(元/千克)" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="重量(千克)">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>

        <el-form-item label="打包要求" prop="packgeRequirements">
          <el-input
            v-model="form.packageRequirements"
            placeholder="请输入打包要求"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listResource,
  getResource,
  delResource,
  addResource,
  updateResource,
  fuzzyListResource,
} from "@/api/system/resource";
import { getToken } from "@/utils/auth";
import user from "@/store/modules/user";

export default {
  name: "Mine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源表格数据
      resourceList: [],
      // 当前行详情
      currentResource: [],
      //  选中行的resource集合
      resourceItems: [],
      // 弹出层标题
      title: "",
      // 是否显示新增修改弹出层
      open: false,
      // 是否展示详情记录
      openDetail: false,

      // 资源类型参数
      options: [
        {
          label: "可回收物-废纸",
          value: "可回收物-废纸",
        },
        {
          label: "可回收物-塑料",
          value: "可回收物-塑料",
        },
        {
          label: "可回收物-玻璃",
          value: "可回收物-玻璃",
        },
        {
          label: "可回收物-金属",
          value: "可回收物-金属",
        },
        {
          label: "可回收物-布料",
          value: "可回收物-布料",
        },
        {
          label: "有害垃圾",
          value: "有害垃圾",
        },
        {
          label: "厨余垃圾",
          value: "厨余垃圾",
        },
        {
          label: "其他垃圾",
          value: "其他垃圾",
        },
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceId: null,
        img: null,
        resourceTypeId: null,
        resourceType: null,
        orderId: null,
        ownerId: null,
        name: null,
        price: null,
        weight: null,
        totalPrice: null,
        packageRequirements: null,
        collectTime: null,
        isCollect: null,
        isLock: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // publisherId: [
        //   { required: true, message: "发布者id不能为空", trigger: "blur" },
        // ],
      },

      limit: 1,
      //页面上存的暂时图片地址List
      fileList: [{ url: "" }],
      //图片地址
      imageUrl: "",
      //图片名称不含路径的
      nFileName: "",
      dialogVisible: false,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询资源列表 */
    getList() {
      this.loading = true;
      listResource(this.queryParams).then((response) => {
        this.resourceList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 按条件模糊搜索公告列表 */
    getFuzzyList() {
      console.log(this.queryParams);
      this.loading = true;
      fuzzyListResource(this.queryParams).then((response) => {
        this.resourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resourceId: null,
        img: null,
        resourceTypeId: null,
        resourceType: null,
        orderId: null,
        ownerId: null,
        name: null,
        price: null,
        weight: null,
        totalPrice: null,
        packageRequirements: null,
        collectTime: null,
        isCollect: null,
        isLock: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 模糊搜索按钮操作 */
    handleFuzzyQuery() {
      this.queryParams.pageNum = 1;

      this.getFuzzyList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.resourceId);
      this.resourceItems = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资源";
      this.upload.fileList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //   if (user.state.userId != this.resourceItems[0]) {
      //     this.$alert("只能修改自己发布的公告！", "警告", {
      //       confirmButtonText: "确认",
      //     });
      //     return;
      //   }
      this.reset();
      const resourceId = row.resourceId || this.ids;
      getResource(resourceId).then((response) => {
        if (response.data.fileUrl != null) {
          this.fileList = [
            { url: process.env.VUE_APP_BASE_API + response.data.fileName },
          ];
        }

        this.form = response.data;
        this.open = true;
        this.title = "修改资源";
      });
    },

    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type == "image/png";
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 5MB!");
      }
      return isJPG && isLt2M;
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.imageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file) {
      //设置图片访问路径 （fileUrl 后台传过来的的上传地址）
      this.imageUrl = file.response.url;
      //下面是为了将图片信息存入数据库准备
      this.form.img = file.response.url;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传图片数量不能超过 ${this.limit} 个!`);
    },

    /** 查看详情按钮 */
    viewDetail(row) {
      this.openDetail = true;
      this.currentNotice[0] = row;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.resourceId != null) {
            this.form.ownerId = user.state.userId;
            updateResource(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.ownerId = user.state.userId;
            addResource(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      const noticeIds = this.ids;
      this.$modal
        .confirm("是否确认删除选中资源")
        .then(function () {
          return delResource(noticeIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.getList();
          this.$modal.msgErroe("删除失败");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/resource/export",
        {
          ...this.queryParams,
        },
        `resource_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
